package com.sc.es.phone;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.sc.es.common.ApiResponse;
import com.sc.es.dto.QiNiuPutRet;
import com.sc.es.service.IQiNiuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author sc
 * Created on  2018/2/23
 */
@Controller
public class PicController {

    @Autowired
    private IQiNiuService qiNiuService;

    @GetMapping("/pic")
    public String picPage(Model model,HttpServletRequest request){
        String id = request.getParameter("id");
//        if(id.isEmpty()){
//            throw new RuntimeException("不存在ID值,请联系信息部");
//        }
        model.addAttribute("id",123);
        return "pic";
    }
    @Autowired
    private Gson gson;

    @PostMapping("/pic/add")
    @ResponseBody
    public ApiResponse uploadPhoto(@RequestParam("file")MultipartFile file, HttpServletRequest request){
        String uid = request.getParameter("m");
        String other = request.getParameter("note");
        if(file.isEmpty()){
            return ApiResponse.ofStatus(ApiResponse.Status.NOT_VALID_PARAM);
        }
        try {
            InputStream stream = file.getInputStream();

            //修改这里 的存储方式即可
            Response response = qiNiuService.uploadFile(stream);
            //
            if(response.isOK()){
                QiNiuPutRet qiNiuPutRet = gson.fromJson(response.bodyString(), QiNiuPutRet.class);
                return ApiResponse.ofSuccess(qiNiuPutRet);
            }else {
                return ApiResponse.ofMessage(response.statusCode,response.getInfo());
            }
        }catch (QiniuException e){
            Response response = e.response;
            return ApiResponse.ofMessage(response.statusCode,response.getInfo());
        }
        catch (IOException e) {
            return ApiResponse.ofMessage(500,"联系14099");
        }
    }
}
